package com.zhangdi.dwtools.net;

import com.zhangdi.dwtools.text.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

public class WebHelper {

    /**
     * 是否是Ajax请求
     */

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        return "XMLHttpRequest".equalsIgnoreCase(requestedWith);
    }

    /**
     * 输出JSON
     */
    public static void writeJson(Object object, ServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(JsonUtil.obj2json(object));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void redirectUrl(String redirectUrl) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> String createUrl(String path, Map<String, T> param) {
        if (null == param || !StringUtils.isNotEmpty(path)) {
            return null;
        }

        Iterator<Map.Entry<String, T>> iterator = param.entrySet().iterator();

        StringBuilder sb = new StringBuilder(path);
        sb.append("?");
        int index = 0;
        while (iterator.hasNext()) {
            Map.Entry<String, T> entry = iterator.next();
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());

            if (index < param.size() - 1) {
                sb.append("&");
            }
            ++index;
        }

        return sb.toString();
    }

}